using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;

namespace Fuse8.DomainFramework.DataAccess.ExpressionSlicers
{
    /// <summary>
    /// Default implementation of <see cref="ISlicerScope"/>.
    /// </summary>
    /// <remarks>
    /// Provides context for Web and non web applications
    /// </remarks>
    public class DefaultSlicerScope : ISlicerScope
    {
        [ThreadStatic]
        private static IDictionary nonHttpContext;

        protected IDictionary Dictionary
        {
            get
            {
                if (HttpContext.Current != null)
                {
                    return HttpContext.Current.Items;
                }

                return  nonHttpContext ?? (nonHttpContext = new Dictionary<object, object>());
            }
        }


        /// <summary>
        /// Get current slicer expression
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public LambdaExpression GetCurrentSlicer(Type type)
        {
            string key = string.Format("CurrentSlicerExpression_{0}", type.FullName);
            if (Dictionary.Contains(key))
            {
                return Dictionary[key] as LambdaExpression;
            }

            var service = SlicerServiceFacade.Current;
            if (service != null)
            {
                Dictionary[key] = service.ResolveForType(type);                
            }
            else
            {
                Dictionary[key] = null;
            }

            return Dictionary[key] as LambdaExpression;
        }
    }
}